package com.conghu.crm.settings.web.controller;

import com.conghu.crm.settings.domain.User;
import com.conghu.crm.settings.service.UserService;
import com.conghu.crm.settings.service.impl.UserServiceImpl;
import com.conghu.crm.utils.MD5Util;
import com.conghu.crm.utils.PrintJson;
import com.conghu.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("用户控制器：已进入");

        String requestPath = request.getServletPath();

        //判断请求的服务，调用服务对象进行处理。
        if(requestPath.equals("/settings/user/login.do")){
            //模板设计模式
            login(request,response);
        }

    }


    private void login(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("进入登陆验证操作");

        String loginAct = request.getParameter("userAct");
        String loginPwd = MD5Util.getMD5(request.getParameter("userPsw"));
        String userIp = request.getRemoteAddr();    //会检查主机的ip是否允许访问服务器
        Map<String, Object> map = new HashMap<>();

        //业务对象的代理类
        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());
        try{
            //如果登陆失败，会抛出自定义的异常LoginException。
            User user = userService.login(loginAct, loginPwd, userIp);

            //不抛异常，分配session  返给前端一个json：{"success":true, "msg":"pass"}
            request.getSession().setAttribute("user", user);
            map.put("success", true);
            map.put("msg", "pass");
        } catch(Exception e){
            //接收到异常说明登陆失败  返给前端一个json：{success:false, msg:"登陆失败"}
            e.printStackTrace();

            map.put("success", false);
            map.put("msg", e.getMessage());

        } finally {
            //不管哪一步  最后都要返回前端
            PrintJson.printJsonObj(response, map);
        }
    }
}
